<?php


namespace app\common\command;


use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

class ResetUen extends Command
{
    /**
     * 命令配置
     */
    protected function configure()
    {
        $this->setName('reset:uen')->setDescription('重复的准了号重新生成');
    }

    protected function execute(Input $input, Output $output)
    {
        $time = time();
        $this->resetRepeatUen();
        echo time() - $time;
    }

    public function getUen($num)
    {
        $uenArr = [];
        for ($i = 0; $i < $num; $i++)
        {
            $uen = substr(md5(microtime() . $i . mt_rand(0, 1000000) . uniqid()), 0, 12);
            array_push($uenArr, $uen);
        }

        return $uenArr;
    }

    public function resetRepeatUen()
    {
        print_r('时间【' . date('Y-m-d H:i:s') . '】重置准了号开始' . PHP_EOL);
        $limit = 100;
        try
        {
            $num = $data = Db::table('wechat_backup_07_18_14_43_00.app_user')
                ->where('uen', '<>', '')
                ->whereIn('uen', function ($query)
                {
                    $query->table('wechat_backup_07_18_14_43_00.app_user')->group('uen')->having('count(uen)>1')->field('uen');
                })->count();

            if ($num > 0)
            {
                print_r('时间【' . date('Y-m-d H:i:s') . '】剩余待重置准了号数量【' . $num . '】' . PHP_EOL);
            } else
            {
                print_r('时间【' . date('Y-m-d H:i:s') . '】剩余待重置准了号数量【' . $num . '】重置结束' . PHP_EOL);
                return true;
            }

            $data = Db::table('wechat_backup_07_18_14_43_00.app_user')
                ->where('uen', '<>', '')
                ->whereIn('uen', function ($query)
                {
                    $query->table('wechat_backup_07_18_14_43_00.app_user')->group('uen')->having('count(uen)>1')->field('uen');
                })->field('id,uen')->limit($limit)->select();

            $uenArray = array_unique($this->getUen($limit));

            foreach ($data as $key => $value)
            {
                $uen = $uenArray[$key] ?? current($this->getUen(1));
                Db::table('wechat_backup_07_18_14_43_00.app_user')->where('id', $value['id'])->update(['uen' => $uen]);
                print_r("用户【{$value['id']}】准了号更新完成；打盹10毫秒" . PHP_EOL);
                usleep(10);
            }

        }
        catch (Exception $e)
        {
            print_r('时间【' . date('Y-m-d H:i:s') . "】重置准了号出现异常【{$e->getMessage()}】;停止任务" . PHP_EOL);
            return false;
        }
        print_r('时间【' . date('Y-m-d H:i:s') . "】重置准了号数量【{$limit}】完成；休息1000毫秒" . PHP_EOL);
        usleep(1000);
        $this->resetRepeatUen();
    }
}
